package org.example.Proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年12月25日 14:49
 */
@Slf4j
public class MockServiceProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Class<?> methodReturnType = method.getReturnType();
        log.info("mock service {} ", method.getName());
        return getDefaultObject(methodReturnType);
    }

    private Object getDefaultObject(Class<?> methodReturnType) {
        if (methodReturnType.isPrimitive()) {
            if (methodReturnType == int.class) {
                return 0;
            } else if (methodReturnType == long.class) {
                return 0L;
            } else if (methodReturnType == float.class) {
                return 0.0f;
            } else if (methodReturnType == double.class) {
                return 0.0d;
            } else if (methodReturnType == boolean.class) {
                return false;
            } else if (methodReturnType == char.class) {
                return '\u0000'; // 默认字符
            } else if (methodReturnType == byte.class) {
                return (byte) 0;
            } else if (methodReturnType == short.class) {
                return (short) 0;
            }
        }

        // 常见对象类型
        if (methodReturnType == String.class) {
            return "";
        } else if (methodReturnType == List.class || methodReturnType == ArrayList.class) {
            return new ArrayList<>();
        } else if (methodReturnType == Map.class || methodReturnType == HashMap.class) {
            return new HashMap<>();
        } else if (methodReturnType == Set.class || methodReturnType == HashSet.class) {
            return new HashSet<>();
        }

        // 如果是其他对象类型，尝试创建无参构造实例
        try {
            return methodReturnType.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            // 无法实例化时返回 null
            return null;
        }
    }
}
